#!/bin/bash

# 批量部署微前端应用脚本
# 使用方法: ./deploy-all.sh [environment] [version]
# 示例: ./deploy-all.sh production v1.0.0

set -e

# 配置
ENVIRONMENT=${1:-production}
VERSION=${2:-latest}

# 应用列表
APPS=(
    "login-app"
    "system-app"
    "dashboard-app"
    "tenant-app"
    "tool-app"
    "workflow-app"
    "monitor-app"
)

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "批量部署微前端应用脚本"
    echo ""
    echo "使用方法:"
    echo "  $0 [environment] [version]"
    echo ""
    echo "参数:"
    echo "  environment  环境 (默认: production)"
    echo "  version      版本 (默认: latest)"
    echo ""
    echo "支持的环境:"
    echo "  production  生产环境"
    echo "  staging     测试环境"
    echo "  local       本地环境"
    echo ""
    echo "示例:"
    echo "  $0 production v1.0.0"
    echo "  $0 staging"
    echo "  $0 local"
}

# 检查依赖
check_dependencies() {
    log_info "检查部署依赖..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装"
        exit 1
    fi
    
    if [[ ! -f "scripts/deploy-app.sh" ]]; then
        log_error "找不到单个应用部署脚本: scripts/deploy-app.sh"
        exit 1
    fi
    
    log_info "依赖检查通过"
}

# 部署单个应用
deploy_single_app() {
    local app_name=$1
    local environment=$2
    local version=$3
    
    log_info "开始部署应用: $app_name..."
    
    # 调用单个应用部署脚本
    if ./scripts/deploy-app.sh "$app_name" "$environment" "$version"; then
        log_info "应用 $app_name 部署成功"
        return 0
    else
        log_error "应用 $app_name 部署失败"
        return 1
    fi
}

# 并行部署
deploy_parallel() {
    log_info "开始并行部署所有应用..."
    
    local pids=()
    local failed_apps=()
    
    # 启动所有应用的部署
    for app in "${APPS[@]}"; do
        log_info "启动 $app 的部署..."
        deploy_single_app "$app" "$ENVIRONMENT" "$VERSION" &
        pids+=($!)
    done
    
    # 等待所有部署完成
    for i in "${!pids[@]}"; do
        local pid=${pids[$i]}
        local app=${APPS[$i]}
        
        if wait $pid; then
            log_info "✅ $app 部署成功"
        else
            log_error "❌ $app 部署失败"
            failed_apps+=("$app")
        fi
    done
    
    # 报告结果
    if [[ ${#failed_apps[@]} -eq 0 ]]; then
        log_info "🎉 所有应用部署成功！"
    else
        log_error "以下应用部署失败: ${failed_apps[*]}"
        exit 1
    fi
}

# 串行部署
deploy_sequential() {
    log_info "开始串行部署所有应用..."
    
    local failed_apps=()
    
    for app in "${APPS[@]}"; do
        log_info "部署应用: $app"
        
        if deploy_single_app "$app" "$ENVIRONMENT" "$VERSION"; then
            log_info "✅ $app 部署成功"
        else
            log_error "❌ $app 部署失败"
            failed_apps+=("$app")
        fi
        
        # 应用间等待
        sleep 5
    done
    
    # 报告结果
    if [[ ${#failed_apps[@]} -eq 0 ]]; then
        log_info "🎉 所有应用部署成功！"
    else
        log_error "以下应用部署失败: ${failed_apps[*]}"
        exit 1
    fi
}

# 健康检查
health_check() {
    log_info "执行健康检查..."
    
    local failed_apps=()
    
    for app in "${APPS[@]}"; do
        log_info "检查应用: $app"
        
        # 这里需要根据实际部署情况调整健康检查逻辑
        # 例如检查容器状态、端口是否可访问等
        if docker ps | grep -q "$app"; then
            log_info "✅ $app 运行正常"
        else
            log_error "❌ $app 运行异常"
            failed_apps+=("$app")
        fi
    done
    
    if [[ ${#failed_apps[@]} -eq 0 ]]; then
        log_info "🎉 所有应用健康检查通过！"
    else
        log_error "以下应用健康检查失败: ${failed_apps[*]}"
        exit 1
    fi
}

# 清理
cleanup() {
    log_info "清理资源..."
    
    # 清理未使用的镜像
    docker image prune -f
    
    # 清理构建缓存
    docker builder prune -f
    
    log_info "清理完成"
}

# 主函数
main() {
    log_info "开始批量部署微前端应用..."
    log_info "环境: $ENVIRONMENT"
    log_info "版本: $VERSION"
    log_info "应用数量: ${#APPS[@]}"
    
    check_dependencies
    
    case "$ENVIRONMENT" in
        "production")
            log_warn "生产环境部署，建议使用串行部署"
            deploy_sequential
            health_check
            cleanup
            ;;
        "staging")
            log_info "测试环境部署，使用并行部署"
            deploy_parallel
            health_check
            ;;
        "local")
            log_info "本地环境部署，使用串行部署"
            deploy_sequential
            ;;
        *)
            log_error "未知环境: $ENVIRONMENT"
            show_help
            exit 1
            ;;
    esac
    
    log_info "批量部署完成！"
}

# 执行主函数
main "$@"
